package com.swsc.xapp.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class BeanUtils {
    /**
     * 复制源对象的属性到目标对象中
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyProperties(Object source, Object target) {
        if (source == null) {
            return;
        }
        Field[] sourceFields = source.getClass().getDeclaredFields();
        for (Field sourceField : sourceFields) {
            sourceField.setAccessible(true);
            try {
                Object sourceValue = sourceField.get(source);
                Field targetField = findField(target, sourceField.getName());
                if (targetField != null) {
                    targetField.setAccessible(true);
                    targetField.set(target, sourceValue);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static <T, K> T copyProperties(K k, Class<? extends T> t) {
        try {
            T r = t.newInstance();
            copyProperties(k, r);
            return r;
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 根据字段名在类中查找字段
     *
     * @param target      目标类
     * @param sourceField 字段名
     * @return 字段对象
     */
    private static Field findField(Object target, String sourceField) {
        Class<?> clazz = target.getClass();
        while (clazz != null) {
            try {
                return clazz.getDeclaredField(sourceField);
            } catch (NoSuchFieldException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return null;
    }

    /**
     * 复制源列表中的对象到目标列表中
     *
     * @param source 源列表
     * @param clazz  目标对象的类
     * @param <T>    目标对象的类型
     * @return 目标列表
     */
    public static <T> List<T> copyListProperties(List<?> source, Class<T> clazz) {
        if (source == null) {
            return null;
        }
        List<T> target = new ArrayList<>(source.size());
        for (Object sourceObject : source) {
            try {
                T targetObject = clazz.newInstance();
                copyProperties(sourceObject, targetObject);
                target.add(targetObject);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return target;
    }
}
